package com.example.wanmengnovel;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


@WebServlet("/revise-novel")
public class ReviseNovel extends HttpServlet {
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("JDBC驱动加载成功！");
        String url = "jdbc:mysql://localhost:3306/users";
        String user = "root";
        String password = "lcw0909.";
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String Value = req.getParameter("writingContent");
        String id = req.getParameter("id");
        try {
            // 创建SQL UPDATE语句
            Connection connection = getConnection();
            String sql = "UPDATE novel SET Value = ? WHERE id = ?"; // 替换SomeCondition为您的实际条件列
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, Value); // 替换newValue为您想要设置的新值
            preparedStatement.setInt(2, Integer.valueOf(id)); // 替换conditionValue为您的条件值

            // 执行UPDATE语句
            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("已更新");
            }
            req.getRequestDispatcher("/WEB-INF/MyInterface.jsp").forward(req, resp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
